package com.hyts.apilog.handler;

import com.hyts.apilog.adapter.AspectHandlerAdapter;
import com.hyts.apilog.annotation.ApiLog;
import com.hyts.apilog.bean.AspectjBean;
import com.hyts.apilog.logger.DefaultLoggerAspectText;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.apilog.handler
 * author:Libo/Alex
 * create-date:2019-06-15 22:37
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: 抽象服务aspect面向切面的处理器
 */
@Component
@Aspect
public abstract class AbstractAspectHandler extends DefaultLoggerAspectText implements BaseAspectHandler{

    @Pointcut("@annotation(com.hyts.apilog.annotation.ApiLog)")
    public void log() {}

    @Autowired
    @Setter
    AspectHandlerAdapter<JoinPoint, AspectjBean> aspectjBeanAspectLogHandlerAdapter;

    @Before("log()")
    @Override
    public void before(JoinPoint joinPoint) throws Throwable {
        AspectjBean aspectjBean = aspectjBeanAspectLogHandlerAdapter.transfer(joinPoint);
        beforeLoggerText(aspectjBean);
    }

    @After("log()")
    @Override
    public void after(JoinPoint joinPoint) throws Throwable {
        AspectjBean aspectjBean = aspectjBeanAspectLogHandlerAdapter.transfer(joinPoint);
        afterLoggerText(aspectjBean);
    }

    @AfterReturning(returning = "returnObj",pointcut = "log()")
    @Override
    public void afterReturning(JoinPoint joinPoint, Object returnObj) throws Throwable {
        AspectjBean aspectjBean = aspectjBeanAspectLogHandlerAdapter.transfer(joinPoint);
        afterReturnLoggerText(aspectjBean);
    }

    @AfterThrowing(throwing = "e",pointcut = "log()")
    @Override
    public void afterThrowing(JoinPoint joinPoint, Throwable e) throws Throwable {
        AspectjBean aspectjBean = aspectjBeanAspectLogHandlerAdapter.transfer(joinPoint);
        afterErrorLoggerText(aspectjBean);
    }
    @Around("log()")
    @Override
    public Object around(ProceedingJoinPoint pJoinPoint) throws Throwable {
        AspectjBean aspectjBean = aspectjBeanAspectLogHandlerAdapter.transfer(pJoinPoint);
        aroundLoggerText(aspectjBean);
        return pJoinPoint.proceed(pJoinPoint.getArgs());
    }
}
